import entity.Student;

import java.io.*;

public class Main {
	public static void main(String[] args) {
		saveObjToFile();
		createObjFromFile();
	}

	/**
	 * 根据系列化后，保存的文件，来创建一个对象
	 */
	private static void createObjFromFile() {
		try {
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("student.txt")));
			Student student = (Student) ois.readObject();
			ois.close();
			System.out.println("序列化创建出来的对象结构");
			System.out.println(student.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

	}

	/**
	 *
	 */
	private static void saveObjToFile() {
		Student student = new Student("name", 18, 90,"password");
		try {
			// 创建一个对象输出流
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("student.txt")));
			// 输出流执行写对象操作，将对象从内存中写出到
			oos.writeObject(student);
			oos.close();
			System.out.println("序列化成功！已经生成student.txt文件,目录位置应该是当前项目的根路径。");

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
